/**
 * 按键中断方式，选择菜单
 */
#include <Arduino.h>
#include "U8g2lib.h"
#include <Wire.h>

#define BUTTON_UP 12
#define BUTTON_DOWN 13


volatile int flag = 0;

void drawMenu();

void handleUp() {
    flag = 1;
}

void handleDown() {
    flag = 2;

}

U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);
String menu[] = {"item1", "item2", "item3", "item4"};

void setup() {

    Serial.begin(115200);
    // write your initialization code here
    u8g2.begin();
    u8g2.enableUTF8Print();
    u8g2.setFont(u8g2_font_wqy12_t_chinese2); // choose a suitable font

    pinMode(BUTTON_UP, INPUT_PULLUP);
    pinMode(BUTTON_DOWN, INPUT_PULLUP);

    attachInterrupt(BUTTON_UP, handleUp, RISING);
    attachInterrupt(BUTTON_DOWN, handleDown, RISING);
}

int currentIndex = 0;

void loop() {

    if (flag == 1) {
        if (currentIndex > 0) {
            currentIndex = currentIndex - 1;
        }
        Serial.println("up");
        delay(50);
        flag = 0;
    }
    if (flag == 2) {
        if (currentIndex < 3) {
            currentIndex = currentIndex + 1;
        }
        Serial.println("down");
        delay(50);
        flag = 0;
    }
    u8g2.clearBuffer(); // clear the internal memory

    // u8g2.drawStr(0, 10, "你好 世界!"); // write something to the internal memory
    drawMenu();
    u8g2.sendBuffer(); // transfer internal memory to the display
//    if (digitalRead(BUTTON_UP) == 0)
//    {
//        delay(10);
//        Serial.println("BUTTON_UP");

//    }
//
//    if (digitalRead(BUTTON_DOWN) == 0)
//    {
//        delay(10);
//        Serial.println("BUTTON_DOWN");
//
//    }
}

void drawMenu() {
    for (int i = 0; i < menu->length() - 1; i++) {
        if (currentIndex != i) {
            u8g2.setCursor(0, (i + 1) * 10);
            u8g2.print(menu[i].c_str());
        } else {

            u8g2.setCursor(5, (i + 1) * 10);
            u8g2.print(">");
            u8g2.print(menu[i].c_str());
        }

        // u8g2.drawStr(0, (i+1) * 10, menu[i].c_str());
    }
}